//《Node与Express开发》
var express = require('express');

var app = express();

//设置handlers视图引擎
var handlebars = require('express3-handlebars').create(
    { defaultLayout: 'main' }
);
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');

app.set('port', process.env.PORT || 8080);

//设置public目录(用于发布)
app.use(express.static(__dirname + '/public'));

//添加测试中间件
app.use(function (req, rsp, next) {
    rsp.locals.showTests = app.get('env') !== 'production' &&
        req.query.test === '1';
    next();
})

//添加路由
app.get('/', function(req, rsp){
    //res.type('text/plain');
    //res.send('Meadowlark Travel');
    rsp.render('home');   //使用handlebars,不用指定type，默认 text/html
});

//用于about页面
var fortune = require('./lib/fortune.js')
app.get('/about', function (req, rsp) {
    rsp.render('about', {
        fortune: fortune.getFortune(),
        pageTestScript: '/qa/tests-about.js'
    });
 });

/*
app.get('/about', function(req, rsp){
    //res.type('text/plain');
    //res.send('About Meadowlark Travel');
    rsp.render('about');
});
*/

//tours
app.get('/tours/hood-river', function (req, rsp) { 
    rsp.render('tours/hood-river');
});

app.get('tours/request-group-rate', function (req, rsp) {
    rsp.render('tours/request-group-rate');
});

//use是Express添加中间件的一种方法
//定制404页面
app.use(function(req,res){
    //res.type('text/plain');
    res.status(404);
    //res.send('404 - Not Found.. OK');
    res.render('404');
});

//定制500页面
app.use(function(err, req, res, next){
    console.error(err.stack);
    //res.type('text/plain'); 
    res.status(500);
    //res.send('500 - Server Error.. OK');
    res.render('500');
});



app.listen(app.get('port'), function(){
    console.log('Express started on http://localhost:' + 
    app.get('port') + ';press Ctrl-C to terminate. OK');
});

